// /src/utils/i18n.ts
import i18n from 'i18next';
import Taro from '@tarojs/taro';
import { initReactI18next } from 'react-i18next';
import en from '@/locales/en.json';
import zh from '@/locales/zh.json';

const getInitialLanguage = (): string => {
  const savedLang = Taro.getStorageSync('app_language');
  if (savedLang) return savedLang;
  const systemInfo = Taro.getSystemInfoSync();
  const systemLang = systemInfo.language;
  if (systemLang.startsWith('zh')) return 'zh';
  return 'en';
};

const initLang = getInitialLanguage();

i18n.use(initReactI18next).init({
  resources: { en: { translation: en }, zh: { translation: zh } },
  lng: initLang,
  fallbackLng: 'en',
  interpolation: { escapeValue: false },
  react: { useSuspense: false },
});

// 导出方法
export const changeLanguage = (lang: string) => {
  i18n.changeLanguage(lang);
  Taro.setStorageSync('app_language', lang);
};

// 导出当前语言（供 Zustand 使用）
export const getCurrentLanguage = () => i18n.language;

export default i18n;
